package com.ktjiaoyu.crm.service.impl;

import com.ktjiaoyu.crm.entity.Product;
import com.ktjiaoyu.crm.entity.Storage;
import com.ktjiaoyu.crm.repository.ProductRepository;
import com.ktjiaoyu.crm.service.IProductService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service(value = "productService")
public class ProductServiceImpl implements IProductService {
    @Resource
    private ProductRepository productRepository;
    @Override
    public Page<Product> findProNameAndProdTypeAndProBatch(String prodName, String prodType, String proBatch, Pageable pageable) {
        Specification<Product> productSpecification = new Specification<Product>() {
            @Override
            public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (prodName!=null && !prodName.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("prodName"), "%"+prodName+"%"));
                }
                if (prodType!=null && !prodType.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("prodType"), "%"+prodType+"%"));
                }
                if (proBatch!=null && !proBatch.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("proBatch"), "%"+proBatch+"%"));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return productRepository.findAll(productSpecification, pageable);
    }
}
